package framework.core.util;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import framework.system.entity.SysUser;
/**
 * @ClassName: OnlineFilter 
 * @Description: 登陆验证过滤
 * @author: Ching Wang
 * @date 2013-5-18 下午1:05:40 
 *
 */
public class OnlineFilter extends HttpServlet implements Filter { 
	private static final long serialVersionUID = 1L;
	public void doFilter(ServletRequest request, ServletResponse response,   FilterChain chain) throws IOException, ServletException {  
		// 这里设置如果没有登陆将要转发到的页面  
		HttpServletRequest req = (HttpServletRequest) request; 
		HttpServletResponse res = (HttpServletResponse) response; 
		HttpSession session = req.getSession(true);  
		
		String requestUri = req.getRequestURI();
		String contextPath = req.getContextPath();
		String url = requestUri.substring(contextPath.length());
		// 从session里取的用户名信息  
		SysUser user = (SysUser) session.getAttribute("user");
		// 这里获取session，为了检查session里有没有保存用户信息，没有的话回转发到登陆页面
		// 判断如果没有取到用户信息,就跳转到登陆页面  
		if(user == null && url.indexOf("login") == -1 && url.indexOf("init") == -1){
			// 跳转到登陆页面   
			if(isAjaxRequest(req)){
				try {
					response.getWriter().print("login");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			else{
				res.sendRedirect(req.getContextPath() + "/login.jsp");
			}
			
		} else {   
			chain.doFilter(request, response);   
		} 
	} 
	 private boolean isAjaxRequest(HttpServletRequest request) {  
        String header = request.getHeader("X-Requested-With");  
        if (header != null && "XMLHttpRequest".equals(header))  
            return true;  
        else  
            return false;  
    }
	public void init(FilterConfig filterConfig) throws ServletException { 
		// TODO Auto-generated method stub 
	}
}